//
//  SXTopicDetailsViewController.m
//  ShiXun
//
//  Created by lanou on 15/10/28.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXTopicDetailsViewController.h"
#import "SXTopicDetailsTableViewCell.h"
#import "SXRequestManager.h"
#import "SXTopicListModel.h"
#import "SXTopicHeaderView.h"
#import "UIImageView+WebCache.h"
#import "UMSocial.h"
#import "SXCollectionManager.h"

@interface SXTopicDetailsViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *detailsView;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIView *placeholderView;
@property (nonatomic, strong) UIAlertController *alertTs;
@property (nonatomic, strong) SXTopicListModel *configureModel;
@property (nonatomic, strong) SXTopicListForumModel *forumModel;

@end

@implementation SXTopicDetailsViewController

- (NSMutableArray *)dataSourceArray
{
    if (!_dataSourceArray) {
        self.dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    _detailsView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:(UITableViewStyleGrouped)];
    _detailsView.delegate = self;
    _detailsView.dataSource = self;
    [_detailsView registerClass:[SXTopicDetailsTableViewCell class] forCellReuseIdentifier:@"DetailsTableViewCell"];
    
    [self.view addSubview:_detailsView];
    [self requestData];
}

// 网络请求
- (void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"count"] = @"20";
    parDic[@"forum_id"] = @"5546233136";
    parDic[@"thread_id"] = _thread_id;
//    NSLog(@"_thread_id = %@",_thread_id);

    [SXRequestManager requestWithType:POST urlString:kTopicDetailsURLSreing parDic:parDic finish:^(NSData *data) {
    NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
        // 区头
        _configureModel = [[SXTopicListModel alloc] init];
        [_configureModel setValuesForKeysWithDictionary:Dic[@"thread"]];
        // 评论
        NSArray *dataArray = Dic[@"comments"][@"data"];
        for (NSDictionary *modelDic in dataArray) {
            SXTopicListModel *detailsModel = [[SXTopicListModel alloc] init];
            [detailsModel setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:detailsModel];
        }
        // 区尾
        NSDictionary *forumDic = Dic[@"forum_info"];
        _forumModel = [[SXTopicListForumModel alloc] init];
        [_forumModel setValuesForKeysWithDictionary:forumDic];
        
        [_detailsView reloadData];
    } error:^(NSError *error) {
        NSLog(@"数据请求失败：%@",error);
    }];
}
// 区头设置
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSInteger a = _configureModel.thumbImageArray.count;
    if (a == 0) {
        CGFloat headerHeight = [SXTopicHeaderView heightHeaderOfContent:_configureModel.content] + 100;
        return headerHeight;
    }else if (a == 1) {
        CGFloat headerHeight = [SXTopicHeaderView heightHeaderOfContent:_configureModel.content] + 130 + (kScreenWidth - 30) / 3 ;
        return headerHeight;
    }
    else if (a < 4 ) {
        CGFloat headerHeight = [SXTopicHeaderView heightHeaderOfContent:_configureModel.content] + 100 + (kScreenWidth - 30) / 3 ;
        return headerHeight;
    }else if (a > 3 && a < 7) {
        CGFloat headerHeight = [SXTopicHeaderView heightHeaderOfContent:_configureModel.content] + 110 + 2 *((kScreenWidth - 30) / 3);
        return headerHeight;
    }else {
        CGFloat headerHeight = [SXTopicHeaderView heightHeaderOfContent:_configureModel.content] + 120 + 3 * ((kScreenWidth - 30) / 3);
        return headerHeight;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SXTopicHeaderView *headerView = [[SXTopicHeaderView alloc ] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    [headerView.shareButton addTarget:self action:@selector(ChangeShare:) forControlEvents:(UIControlEventTouchUpInside)];
    [headerView.collectionButton addTarget:self action:@selector(ChangeCollection:) forControlEvents:UIControlEventTouchUpInside];
    
    headerView.collectionButton.selected = [SXCollectionManager checkCollectionWithTableName:@"topic" urlID:_configureModel.thread_id];
    [headerView.collectionButton addTarget:self action:@selector(ChangeCollection:) forControlEvents:UIControlEventTouchUpInside];
    
    [headerView.collectionB addTarget:self action:@selector(ChangeCollection:) forControlEvents:(UIControlEventTouchUpInside)];
    headerView.collectionB.selected = headerView.collectionButton.selected;
    headerView.collectionButton.selected = headerView.collectionB.selected;
    headerView.backgroundColor = [UIColor whiteColor];
    
    headerView.configureModel = _configureModel;
    return headerView;
}
// 点击收藏
- (void)ChangeCollection:(UIButton *)button
{
    button.selected = !button.selected;
    NSString *message = nil;
    if (button.selected) {
        message = @"收藏成功";
    }else {
        message = @"取消收藏成功";
    }
    [SXCollectionManager  collectionDataWithTableName:@"topic" title:_configureModel.content urlID:_configureModel.thread_id isCollection:button.selected finish:^(BOOL isSuccessed) {
        if (isSuccessed) {
            _alertTs = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:_alertTs animated:YES completion:nil];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doTapCollection:) userInfo:nil repeats:NO];
        }else {
            NSLog(@"收藏失败！");
        }
    }];
    [_detailsView reloadData];
}
- (void)doTapCollection:(NSTimer *)timer
{
    
    [_alertTs dismissViewControllerAnimated:YES completion:nil];
}

// 分享
- (void)ChangeShare:(UIButton *)button
{
    // 分享后是否提示（YES是不提示）
    [UMSocialConfig setFinishToastIsHidden:NO position:(UMSocialiToastPositionCenter)];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5632c41ce0f55a17390010c1"
                                      shareText:[NSString stringWithFormat:@"更多精彩内容等你来看，点击进入详情：%@",self.forumModel.share_url]
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                       delegate:nil];
}
// cell 设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_dataSourceArray.count == 0) {
        return 1;
    }else {
    return _dataSourceArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXTopicDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailsTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UINavigationControllerOperationNone;
    if (_dataSourceArray.count == 0) {
        _placeholderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
        _placeholderView.backgroundColor = [UIColor colorWithRed:0.6904 green:0.6904 blue:0.6904 alpha:1.0];
        [cell addSubview:_placeholderView];
        
        UILabel *placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 5, kScreenWidth - 80, 50)];
        placeholderLabel.font = [UIFont systemFontOfSize:14];
        placeholderLabel.numberOfLines = 2;
        placeholderLabel.text = @"最伤心的是，我来看你，而你不在——评论。";
        [_placeholderView addSubview:placeholderLabel];
        return cell;
    } else{
        [_placeholderView removeFromSuperview];
    cell.configureModel = _dataSourceArray[indexPath.row];
    return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [SXTopicDetailsTableViewCell heightOfContent:[_dataSourceArray[indexPath.row] content]] + 60;
    return height;
}

// 区尾设置
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 80;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    _footerView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    _footerView.backgroundColor = [UIColor colorWithRed:0.9267 green:0.7834 blue:0.9992 alpha:0.6];
    UIImageView *imageT = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    imageT.image = [UIImage imageNamed:@"T2"];
    [_footerView addSubview:imageT];
    _footerView.userInteractionEnabled = YES;
    
    UILabel *titleLabei = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth / 2, 20)];
    titleLabei.text = @"当前话题";
    titleLabei.textColor = [UIColor orangeColor];
    titleLabei.font = [UIFont systemFontOfSize:12];
    [_footerView addSubview:titleLabei];
    
    UIView *dividerV = [[UIView alloc] initWithFrame:CGRectMake(10, 21, kScreenWidth - 20, 1)];
    dividerV.backgroundColor = [UIColor colorWithRed:0.5547 green:0.6138 blue:0.458 alpha:1.0];
    [_footerView addSubview:dividerV];
    
    UIImageView *avatar_urlImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 25, 50, 50)];
    [avatar_urlImage sd_setImageWithURL:[NSURL URLWithString:_forumModel.avatar_url]];
    [_footerView addSubview:avatar_urlImage];
    
    UILabel *forum_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 25, kScreenWidth * 2/3, 30)];
    forum_nameLabel.text = _forumModel.forum_name;
    [_footerView addSubview:forum_nameLabel];
    
    UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 55, kScreenWidth - 80, 25)];
    descLabel.text = _forumModel.desc;
    descLabel.font = [UIFont systemFontOfSize:10];
    [_footerView addSubview:descLabel];
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didChangeRecognizer)];
    [_footerView addGestureRecognizer:recognizer];
    
    return _footerView;
}
- (void)didChangeRecognizer
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
